// pages/yiqingCode/yiqingCode.js
var app = getApp();
var QR = require("../../common/qrcode.js");
var common = require("../../common/utils.js");


Page({

  /**
   * 页面的初始数据
   */
  data: {
    contacts: [],
    codeShow: false,
    ordercode: '',
    array: ['身份证', '回乡证', '护照', '台胞证'], //下拉列表的数据
    index: 0,
    inputType: 'idcard'
  },
  onReady: function () {
    var size = this.setCanvasSize();
    var initUrl = this.data.ordercode;
    this.createQrCode(initUrl, "mycanvas", size.w, size.h);
  },

  //适配不同屏幕大小的canvas
  setCanvasSize: function () {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 150 / 75;
      var width = res.windowWidth / scale;
      var height = width;
      size.w = width;
      size.h = height;
    } catch (e) {
      console.log("获取设备信息失败" + e);
    }
    return size;
  },

  createQrCode: function (canvasId, cavW, cavH) {
    try {
      QR.qrApi.draw(this.data.ordercode, canvasId, cavW, cavH);
    } catch (err) { }
  },

  qrcode: function (code) {
    var that = this;
    var st = setTimeout(function () {
      try {
        // wx.hideToast()
        var size = that.setCanvasSize();
        //绘制二维码
        that.createQrCode("mycanvas", size.w, size.h);
        clearTimeout(st);
      } catch (err) {

      }
    }, 500)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getUserInfo()
  },
  bindPickerChange: function (e) {
    let val = e.detail.value;
    this.setData({
      index: val,
      inputType: val == '0' ? 'idcard' : 'text'
    })
  },
  login: function () {
    app.showLoadings();
    var that = this;
    wx.request({
      url: app.serviceurl + 'Member/GetTakeman',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      dataType: 'json',
      success: function (res) {
        if (!res.data.Result) {
          return
        }
        res.data.TakeManList.forEach((item) => {
          if (item.IdType == 1) {
            item.IdType = '身份证'
          }
          if (item.IdType == 2) {
            item.IdType = '回乡证'
          }
          if (item.IdType == 3) {
            item.IdType = '护照'
          }
          if (item.IdType == 4) {
            item.IdType = '台胞证'
          }
        })

        that.setData({
          contacts: res.data.TakeManList,
        });

      },
      fail: function () {
        console.log("调用失败");
      },
      complete: function () {
        app.hideLoadings();
      }
    })
  },

  // 获取input值
  userName: function (e) {
    this.setData({
      TakemanNames: e.detail.value
    })
  },
  cardId: function (e) {
    this.setData({
      TakemanCardIDs: e.detail.value
    })
  },
  phoneFun: function (e) {
    this.setData({
      userPhone: e.detail.value
    })
  },

  // 提示框
  repetition: function (message) {
    wx.showModal({
      content: message,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          console.log('确定')
        }
      }
    });
  },
  getUserInfo: function () {
    let that = this;
    wx.request({
      url: app.serviceurl + 'Member/GetMyInfo',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      dataType: 'json',
      success: function (res) {
        try {
          if (res.data.Result == false) {
            that.setData({
              codeShow: false
            })
            return
          }
          let userData = res.data.MemberInfo;

          if (userData.IsShowCode != '' && userData.IsShowCode != null && typeof (userData.IsShowCode) != 'undefined') {
            that.setData({
              codeShow: true,
            })
            that.setData({
              ordercode: userData.Code,
              TakemanNames: userData.MemberName,
              TakemanCardIDs: userData.MemberCardId,
              userPhone: userData.MemberPhone,
              userCarid: userData.MemberCardId,
              userName: userData.MemberName
            })
            that.qrcode(userData.Code);
          } else {
            that.setData({
              codeShow: false,
            })
          }
        }
        catch (err) { }
      },
      fail: function (error) {
        that.repetition('添加失败');
      }
    });

  },
  // 添加新用户
  amend: function (TakemanName, TakemanCardID, TakemanPhone) {
    let that = this;
    wx.request({
      url: app.serviceurl + 'Member/UpdateMyInfo',
      header: {
        Authorization: "Bearer " + app.accesstoken
      },
      data: {
        MemberName: TakemanName,
        MemberCardId: TakemanCardID,
        MemberPhone: TakemanPhone ? TakemanPhone : "",
        // IdType: Number(that.data.index) + 1
      },
      dataType: 'json',
      success: function (res) {
        if (res.data.Result == false) {
          that.repetition(res.data.Message);
          return
        }
        that.getUserInfo();
      },
      fail: function (error) {
        that.repetition('添加失败');
      }
    });
  },

  save: function () {
    try {
      let phone = this.data.userPhone;
      // 如果用户输入手机号进行判断
      if (typeof (phone) !== 'undefined' && phone !== '') {
        if (!common.ChkUtil.isMobile(phone)) {
          this.repetition("请核实手机号是否正确");
          return
        }
      }
      // 除身份证外，其它证件号的正则表达式并不完善，后台也有验证
      let hui = /^([A-Z]\d{6,11}(\(\w{1}\))?)$/;
      let tai = /^\d{8}|^\d{18}|^[a-zA-Z0-9]{10}$/;
      let hu = /^([a-zA-z]|[0-9]){5,17}$/;
      var TakemanName;
      var TakemanCardID;
      if (!this.data.TakemanCardIDs && !this.data.TakemanNames) {
        // 去空格
        TakemanName = this.data.userName.replace(/\s/g, "");
        TakemanCardID = this.data.userCarid.replace(/\s/g, "");
      } else {
        // 去空格
        TakemanName = this.data.TakemanNames ? this.data.TakemanNames.replace(/\s/g, "") : this.data.userName.replace(/\s/g, "");
        TakemanCardID = this.data.TakemanCardIDs ? this.data.TakemanCardIDs.replace(/\s/g, "") : this.data.userCarid.replace(/\s/g, "");
      }
      if (!TakemanCardID || !TakemanName) {
        this.repetition("请核实信息是否填正确");
        return
      }
      // 回乡证判断
      if (this.data.index == 1) {
        if (hui.test(TakemanCardID)) {
          this.amend(TakemanName, TakemanCardID, phone)
          return
        } else {
          this.repetition("请核对证件号是否正确");
        }
        return
      }
      // 护照判断
      if (this.data.index == 2) {
        if (hu.test(TakemanCardID)) {
          this.amend(TakemanName, TakemanCardID, phone)
          return
        } else {
          this.repetition("请核对证件号是否正确");
        }
        return
      }
      // 台胞证判断
      if (this.data.index == 3 && tai.test(TakemanCardID)) {
        if (tai.test(TakemanCardID)) {
          this.amend(TakemanName, TakemanCardID, phone)
          return
        } else {
          this.repetition("请核对证件号是否正确");
        }
        return
      }

      if (TakemanName && common.ChkUtil.isIdCardNew(TakemanCardID) && phone) {
        // 所有验证通过
        if (this.data.takemanid) {
          this.deleteUser(this.data.takemanid, TakemanName, TakemanCardID, phone)
        } else {
          this.amend(TakemanName, TakemanCardID, phone)
        }
      } else if (!TakemanName) {
        this.repetition("姓名需要2个中文以上")
      } else if (!common.ChkUtil.isIdCardNew(TakemanCardID)) {
        this.repetition("请确认这是正确的证件号")
      } else if (!phone) {
        this.repetition("请输入手机号")
      }
    } catch (err) {
      this.repetition('添加失败');
      console.log(err)
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.login();
    this.qrcode(this.data.ordercode);

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})